import axios from 'axios'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

import { Message } from 'element-ui'
const service = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

service.interceptors.request.use(function(config) {
    nprogress.start()
    if (sessionStorage.getItem('userInfo')) {
        let { userId } = JSON.parse(sessionStorage.getItem('userInfo'));
        config.headers['person'] = encodeURIComponent(userId);
        config.headers['Content-Type'] = 'application/json'
    }
    if (sessionStorage.getItem('nowRoot')) {
        let card = sessionStorage.getItem('nowRoot');
        config.headers['card'] = encodeURIComponent(card);
    }
    return config
}, function(error) {
    return Promise.reject(error)
})

service.interceptors.response.use(function(response) {
    nprogress.done()
    if (response.status !== 200) Message({ type: 'error', message: '请求失败' })
    return response.data
}, function(error) {
    nprogress.done()
    return Promise.reject(error);
})

export default service